import { Button } from "antd";
import styles from "./Timer.module.css";
import { useEffect, useState } from "react";
// import { useBackendContext } from "../../../../context/Backend";
import { toast } from "../../../../components/Toast/Toast";
import { useNavigate } from "react-router-dom";
import React from "react";
import { timerApi } from "../../../../utils/backend/server";

// const table = "65975e3490d3d1241de49d20";

export type HistoryType = {
  belongTo: number;
  id: number;
  time: string;
};

export type TimerType = {
  id: string;
  name: string;
  seq: number;
  memo: string;
  history: HistoryType[];
};

export default () => {
  // const [time, setTime] = useState(0);
  // const { cloud } = useBackendContext();
  const to = useNavigate();
  const [timer, setTimer] = useState<{
    time: number;
    timers: TimerType[];
  } | null>(null);

  const refresh = () => {
    timerApi.getTimerList().then((data) => {
      if (data.length <= 0) return;
      const first = data[0];
      const time = Number(first.history[0].time);
      // setTime(Number(first.history[0].time));
      setTimer({
        time,
        timers: data,
      });
      console.log(data);
    });
  };

  useEffect(() => {
    // cloud.getObj(table).then((val) => {
    //   setTime(new Date(Number(val.get("time"))).valueOf());
    // });
    // api callback
    refresh();
  }, []);
  return (
    <div className={styles.box}>
      <div
        className={styles.more}
        onClick={() => {
          to("/timetable");
        }}
      >
        <img src="/more.png" alt="" />
      </div>
      <Countdown timeStamp={timer?.time || 0} />
      <Button
        type="primary"
        onClick={() => {
          if (!timer) {
            toast("please create timer first!");
            return;
          }
          const first = timer.timers[0];
          if (!first) {
            toast("timer error!");
            return;
          }
          timerApi
            .addTimerHistory(first.id, new Date().valueOf().toString())
            .then(() => {
              refresh();
            });
        }}
      >
        reset
      </Button>
      <div className={styles.aphorism}>
        <p>There're things we can have, but can't keep</p>
        <p>who cares if one more light goes out</p>
        <p>in the sky of a million stars</p>
        <p>who cares when someone's time runs out?</p>
        <p>if a moment is all we are</p>
        <p>-- Chester Bennington</p>
      </div>
    </div>
  );
};

export const SEC_MILLS = 1000;
export const MIN_MILLS = SEC_MILLS * 60;
export const HOUR_MILLS = MIN_MILLS * 60;
export const DAY_MILLS = HOUR_MILLS * 24;

export const calRest = (time: number, unit: number) => {
  const val = Math.floor(time / unit);
  const rest = time - val * unit;
  return {
    val,
    rest,
  };
};

const calDate = (past: number) => {
  const cur = new Date().valueOf();
  const day = calRest(cur - past, DAY_MILLS);
  const hour = calRest(day.rest, HOUR_MILLS);
  const min = calRest(hour.rest, MIN_MILLS);
  const sec = calRest(min.rest, SEC_MILLS);
  return {
    day: day.val,
    hour: hour.val,
    min: min.val,
    sec: sec.val,
  };
};

export const Countdown = (props: { timeStamp: number }) => {
  const [date, setDate] = useState({
    day: 0,
    hour: 0,
    min: 0,
    sec: 0,
  });
  useEffect(() => {
    const timer = setInterval(() => {
      setDate(calDate(props.timeStamp));
    }, 1000);

    return () => {
      clearTimeout(timer);
    };
  }, [props.timeStamp]);

  return (
    <div>
      {date.day || 0} days {date.hour || 0} hours {date.min || 0} minutes{" "}
      {date.sec || 0} seconds
    </div>
  );
};
